// pages/feedback/feedback.js
const app = getApp()
const http = require('../../utils/http')
const config = require('../../config')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoggedIn: false,
    userInfo: null,
    feedbackTypes: ['功能建议', '问题反馈', '体验问题', '其他'],
    selectedType: 0,
    feedbackTypeText: '功能建议', // 添加默认值
    content: '',
    contentLength: 0, // 添加内容长度属性
    contact: '',
    images: [],
    imagesCount: 0, // 添加图片数量属性
    maxImageCount: 3,
    submitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 确保初始化时images是一个空数组
    const selectedType = this.data.selectedType || 0;
    const feedbackTypeText = this.data.feedbackTypes && this.data.feedbackTypes[selectedType] || '功能建议';
    
    this.setData({
      images: [],
      imagesCount: 0,
      feedbackTypeText: feedbackTypeText
    });
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkLoginStatus();
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus: function () {
    const isLoggedIn = app.globalData.isLoggedIn;
    const userInfo = app.globalData.userInfo;

    this.setData({
      isLoggedIn: isLoggedIn,
      userInfo: userInfo
    });

    if (isLoggedIn && userInfo && userInfo.contact) {
      this.setData({
        contact: userInfo.contact
      });
    }
  },

  /**
   * 选择反馈类型
   */
  selectFeedbackType: function (e) {
    const selectedType = e.detail.value || 0;
    const feedbackTypeText = this.data.feedbackTypes[selectedType] || '功能建议';
    
    this.setData({
      selectedType: selectedType,
      feedbackTypeText: feedbackTypeText
    });
  },

  /**
   * 输入反馈内容
   */
  inputContent: function (e) {
    const content = e.detail.value || '';
    this.setData({
      content: content,
      contentLength: content.length
    });
  },

  /**
   * 输入联系方式
   */
  inputContact: function (e) {
    this.setData({
      contact: e.detail.value || ''
    });
  },

  /**
   * 选择图片
   */
  chooseImage: function () {
    const { images, maxImageCount } = this.data;
    // 确保images是一个数组
    const currentImages = Array.isArray(images) ? images : [];
    const remainCount = maxImageCount - currentImages.length;

    if (remainCount <= 0) {
      wx.showToast({
        title: `最多上传${maxImageCount}张图片`,
        icon: 'none'
      });
      return;
    }

    wx.chooseImage({
      count: remainCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 确保res.tempFilePaths是一个数组
        const newImages = Array.isArray(res.tempFilePaths) ? res.tempFilePaths : [];
        const updatedImages = [...currentImages, ...newImages];
        this.setData({
          images: updatedImages,
          imagesCount: updatedImages.length
        });
      }
    });
  },

  /**
   * 预览图片
   */
  previewImage: function (e) {
    const { images } = this.data;
    // 确保images是一个数组
    const currentImages = Array.isArray(images) ? images : [];
    const current = e.currentTarget.dataset.src;

    wx.previewImage({
      current: current,
      urls: currentImages
    });
  },

  /**
   * 删除图片
   */
  deleteImage: function (e) {
    const { index } = e.currentTarget.dataset;
    const { images } = this.data;
    // 确保images是一个数组
    const currentImages = Array.isArray(images) ? images : [];

    if (currentImages.length > index) {
      currentImages.splice(index, 1);
      this.setData({
        images: currentImages,
        imagesCount: currentImages.length
      });
    }
  },

  /**
   * 提交反馈
   */
  submitFeedback: function () {
    const { selectedType, feedbackTypes, content, contact, images } = this.data;
    // 确保images是一个数组
    const currentImages = Array.isArray(images) ? images : [];

    // 验证反馈内容
    if (!content || !content.trim()) {
      wx.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      });
      return;
    }

    // 验证联系方式
    if (!contact || !contact.trim()) {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      });
      return;
    }

    this.setData({
      submitting: true
    });

    // 构造请求数据
    const requestData = {
      feedbackType: feedbackTypes[selectedType],
      content: content,
      images: currentImages,
      contactInfo: contact
    };

    // 使用http工具类发送请求到后端API
    http.post(config.API.FEEDBACK, requestData)
      .then(res => {
        console.log('反馈提交响应:', res);
        
        // 判断响应是否成功
        if (res && res.code === 200 && res.data && res.data.id) {
          // 提交成功
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 2000);
            }
          });
        } else {
          // 提交失败
          wx.showToast({
            title: '提交失败: ' + (res.message || '未知错误'),
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('反馈提交失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({
          submitting: false
        });
      });
  }
})
